package cn.ren.service;

import cn.ren.dao.PermissionDao;
import cn.ren.dao.RoleDao;
import cn.ren.entity.PageResult;
import cn.ren.entity.QueryPageBean;
import cn.ren.pojo.Permission;
import cn.ren.pojo.Role;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色管理服务
 */

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<Role> page = roleDao.findAll();
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public List<Permission> findAll() {
        return permissionDao.findAll();
    }

    @Override
    public List<Integer> findPermissionIdsByRoleId(Integer id) {
        return roleDao.findPermissionIdsByRoleId(id);
    }

    /*@Override
    public void add(int id, Integer[] permissionIds) {

    }*/

    //添加权限，同时需要更新和检查项的关联关系
    @Override
    public void add(Role role, Integer[] permissionIds) {
        //根据角色id删除中间表数据（清理原有关联关系）
        roleDao.deleteAssociation(role.getId());
        //向中间表(t_role_permission)插入数据（建立角色和权限的关联关系）
        this.setRoleAndPermission(role.getId(),permissionIds);
        //添加权限，更新角色信息
        //roleDao.add(role);
    }

    //设置检查组和检查项多对多关系
    public void setRoleAndPermission(Integer roleId,Integer[] permissionIds){
        if (permissionIds != null && permissionIds.length > 0){
            for (Integer permissionId : permissionIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("roleId",roleId);
                map.put("permissionId",permissionId);
                roleDao.setRoleAndPermission(map);
            }
        }
    }
}
